<template>
  <div class="container" v-loading="loading">
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <!-- <el-button
    link
    @click="handleImport"
    style="--el-text-color-regular: #42464e"
  >
    <img
      style="display: inline-block; margin-right: 3px"
      src="@/assets/wbs/import.svg"
      alt=""
    />
    <span>检入</span>
  </el-button>
  <el-button
    link
    @click="handleImport"
    style="--el-text-color-regular: #42464e"
  >
    <img
      style="display: inline-block; margin-right: 3px"
      src="@/assets/wbs/export.svg"
      alt=""
    />
    <span>检出</span>
  </el-button> -->
      <el-button
        link
        @click="handleImport"
        style="--el-text-color-regular: #42464e; margin-right: auto"
      >
        <img
          style="display: inline-block; margin-right: 3px"
          src="@/assets/wbs/download.svg"
          alt=""
        />
        <span>导入</span>
      </el-button>

      <!-- <el-button
    link
    @click="handleImport"
    style="--el-text-color-regular: #42464e"
  >
    <img
      style="display: inline-block; margin-right: 3px"
      src="@/assets/wbs/file.svg"
      alt=""
    />
    <span>打开任务工作目录</span>
  </el-button>
  <el-button
    link
    @click="handleImport"
    style="--el-text-color-regular: #42464e"
  >
    <img
      style="display: inline-block; margin-right: 3px"
      src="@/assets/wbs/fileSet.svg"
      alt=""
    />
    <span>检入文件设置</span>
  </el-button> -->
    </div>

    <!-- 表格 -->
    <CLTable
      @show:records="handleShowRecords"
      :pageQuery="queryParams"
      :fields="referenceFields"
      :initial-data="tableData"
      line-height="low"
      :table-config="tableConfig"
      :more-actions="moreActions"
      @node-selected="handleNodeSelected"
      @on-more-action="handleMoreAction"
      @pagerChange="pagerChange"
      ref="cltableRef"
    >
      <template #bottomTool>
        <BottomTool
          :selectedFiles="selectedFiles"
          :tableData="tableData"
          @changeCheckbox="changeCheckbox"
          @batchExport="batchExport"
          @batchDelete="batchDelete"
        />
      </template>
    </CLTable>

    <!-- 导入 -->
    <FileUploaderDialog
      ref="fileUploadDialogRef"
      @UploadComplete="UploadComplete"
    />

    <!-- 编辑 -->
    <NameEditModal
      :activeNode="activeNode"
      ref="editNameRef"
      @handleCancel="handleCancel"
      @handleSure="handleSure"
    />

    <!-- 关联 -->
    <RelationModal ref="relationModalRef" />

    <!-- 预览 -->
    <Preview ref="preViewRef" :src="preSrc" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CLTable from "@/components/CLTable/index.vue";
  import {
    getItemsList,
    deleteItem,
    editItem,
    uploadFile,
    bathDownLoadTaskFile,
  } from "./api.ts";
  import Preview from "./Preview.vue";
  import RelationModal from "./RelationModal.vue";
  import BottomTool from "./BottomTool.vue";
  import FileUploaderDialog from "./FileUploaderDialog.vue";
  import NameEditModal from "./NameEditModal.vue";
  import { download } from "@/utils/index";
  const props = defineProps(["detail"]);

  const type = ref("MID_DATA");
  const activeNode = ref(null);
  const fileUploadDialogRef = ref();
  const editNameRef = ref();
  const cltableRef = ref();
  const preViewRef = ref();
  const preSrc = ref(false);
  const relationModalRef = ref<any>(null);
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const selectedFiles = ref<any[]>([]);

  const queryParams = ref({
    pageNo: 1,
    pageSize: 20,
    total: 0,
  });

  // CLTable 字段配置
  const referenceFields = ref<any[]>([
    {
      id: 1,
      name: "名称",
      field: "fileName",
      typex: "imagetext",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 2,
      name: "数据源",
      field: "source",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 3,
      name: "文档类型",
      field: "remark",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
  ]);

  // CLTable 配置
  const tableConfig = ref({
    tableH: "calc(100vh - 230px)",
    page: {
      showOperationsColumn: true,
      enable: true,
      pageSizes: [10, 20, 50, 100],
      size: "small",
      disabled: false,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
    },
    rightFrozenColCount: 1, // 冻结后面列数
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 200, //自定义操作列宽度
    borderMode: "none", // 表格边框模式，none为无边框
  });

  // 更多操作配置
  const moreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "preview", label: "预览" },
    { key: "delete", label: "删除" },
    { key: "export", label: "导出" },
  ]);

  /**
   * @description 处理操做
   */

  const handleMoreAction = (actionKey: string, node: any) => {
    const KEYMAP: any = {
      edit: handleEdit,
      preview: handlePreview,
      delete: handleDelete,
      export: handleExport,
    };
    KEYMAP[actionKey]?.(node);
  };

  /**
   * @description 处理选中值
   */
  const handleShowRecords = (records: any[]) => {
    selectedFiles.value = records;
  };

  /**
   * @description 处理选中与否
   */
  const changeCheckbox = async (val: boolean) => {
    const tableInstalce = await cltableRef.value?.getTableInstance();
    tableInstalce.setCellCheckboxState(0, 0, val);
    if (val) {
      selectedFiles.value = tableData.value;
    } else {
      selectedFiles.value = [];
    }
  };

  /**
   * @description 文件上传成功
   */
  const UploadComplete = async (data: any) => {
    loading.value = true;
    try {
      const { successFiles, description } = data ?? {};
      const params = successFiles.map((ele: any) => ({
        fileId: ele?.docId ?? "",
        fileName: ele?.name ?? "",
        filePath: ele?.raw?.webkitRelativePath ?? "",
        projectId: props?.detail?.projectId,
        taskId: props?.detail?.id,
        remark: description ?? "",
        source: "UPLOAD",
        type: type.value,
      }));
      await uploadFile(params);
      loadData(1, 20);
    } catch (error) {}
  };

  /**
   * 批量导出
   */
  const batchExport = async () => {
    loading.value = true;
    try {
      const params = selectedFiles.value.map((ele) => ({
        fileId: ele.fileId,
        fileName: ele.fileName,
      }));
      const res = await bathDownLoadTaskFile(params);
      download(res, "application/zip;charset=UTF-8", `压缩包_${Date.now()}`);
      ElMessage.success("批量导出成功");
    } catch (error) {
      ElMessage.error("批量导出失败");
    } finally {
      loading.value = false;
    }
  };

  /**
   * 批量删除
   */
  const batchDelete = async () => {
    try {
      await ElMessageBox.confirm(`确定要批量删除这些文件吗？`, "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      const nodeIds = selectedFiles.value.map((e) => e.id);
      loading.value = true;
      await deleteItem(nodeIds.toString());
      ElMessage.success("删除成功");
      loadData(1, 20);
    } catch (error) {
      ElMessage.error("删除失败");
    }
  };

  /**
   * @description 监听分页变化
   */
  const pagerChange = (args: any) => {
    loadData(args.currentPage, args.pageSize);
  };
  /**
   * @description 处理取消
   */
  const handleCancel = () => {
    editNameRef.value.visible = false;
    activeNode.value = null;
  };

  /**
   * @description 处理确定
   */
  const handleSure = async (fileName: string) => {
    loading.value = true;
    try {
      const params = {
        ...(activeNode?.value ?? {}),
        fileName,
      };
      await editItem(params);
      loadData(1, 20);
      editNameRef.value.visible = false;
    } catch (error) {}
  };

  /**
   * @description 获取数据
   */
  const loadData = async (numberPage: number, sizePage: number) => {
    loading.value = true;
    try {
      const params = {
        conditions: [
          {
            field: "type",
            operator: "=",
            value: type.value,
          },
        ],
        pageNo: numberPage ?? 1,
        pageSize: sizePage ?? 10,
      };
      const { result, pageNo, pageSize, total } = await getItemsList(params);
      queryParams.value = {
        pageNo,
        pageSize,
        total,
      };
      tableData.value = result ?? [];
      selectedFiles.value = [];
    } catch (error) {
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  /**
   * @description 获取选中数据
   */
  const handleNodeSelected = (nodes: any[]) => {
    selectedFiles.value = nodes;
  };

  /**
   * @description 导入
   */
  const handleImport = () => {
    if (fileUploadDialogRef.value) {
      fileUploadDialogRef.value.visible = true;
    }
  };

  /**
   * @description 处理编辑
   */
  const handleEdit = (node: any) => {
    activeNode.value = node;
    editNameRef.value.visible = true;
  };

  /**
   * @description 处理预览
   */

  const handlePreview = (node: any) => {
    preSrc.value = node;
    preViewRef.value.visible = true;
  };

  /**
   * @description 处理单行导出
   */

  const handleExport = async (node: any) => {
    loading.value = true;
    try {
      const params = [
        {
          fileId: node.fileId,
          fileName: node.fileName,
        },
      ];
      const arr = node.fileName.split(".");
      const res = await bathDownLoadTaskFile(params);
      download(res, `image/${arr[arr.length - 1]};charset=UTF-8`, arr[0]);
      ElMessage.success("批量导出成功");
    } catch (error) {
      ElMessage.error("批量导出失败");
    } finally {
      loading.value = true;
    }
  };

  /**
   * @description 处理单行删除
   */
  const handleDelete = async (node: any) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除文件 "${node.fileName}" 吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      );
      loading.value = true;
      await deleteItem(node.id);
      ElMessage.success("删除成功");
      loadData(1, 20);
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    } finally {
      loading.value = false;
    }
  };

  // 生命周期
  onMounted(async () => {
    loadData(1, 20);
  });

  // 暴露方法给父组件
  defineExpose({
    loadData,
    refresh: loadData,
  });
</script>

<style scoped lang="scss">
  .container {
    box-sizing: border-box;
    padding-right: 10px;
    margin-top: 2px;
    .table-toolbar {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px 0px;
      color: #5e5e5e;
      font-size: 14px;
      :deep(.el-button.is-link) {
        font-weight: 400;
      }
    }
  }
  .wbs-tree-container {
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }
</style>
